package com.example.club.test.recyclerview

import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.club.R
import com.example.lib_common.utils.LoggerUtils
import com.example.lib_image.GlideApp
import java.util.Collections
import java.util.stream.Collectors

class MyAdapter(
    private val onImageClick: ((String) -> Unit)? = null,
    //private val onLikeClick:((Int) -> Unit)? = null
    private val onLikeClick: ((Int) -> Unit)? = null,
    private val onPreload: (() -> Unit)? = null,
    private var preloadItemCount: Int = 0, //预加载偏移量，倒数第几个
) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
    private var scrollState = RecyclerView.SCROLL_STATE_IDLE //滚动状态

    // 添加以下三个成员变量
    private var lastPreLoadPosition = -1  // 记录上次触发预加载的位置，避免重复触发
    private var isLoading = false         // 标记是否正在加载数据，防止重复加载
    private var recyclerView: RecyclerView? = null // 保存关联的RecyclerView

    /**
     * 更新状态
     */
    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                scrollState = newState
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
    }

    companion object {
        const val TAG = "MyAdapter"
    }

    private val data: MutableList<MyModel> = mutableListOf()

    fun like(position: Int) {
        data[position].isLike = !data[position].isLike
        notifyItemChanged(position, "like") //局部刷新
    }

    /**
     * 使用过DiffUtils局部刷新
     */
    fun setData(newData: MutableList<MyModel>) {
        val calculateDiff =
            DiffUtil.calculateDiff(MyDiffCallBack(data.toList(), newData))//旧数据和新数据,注意不要传引用，使用toList
        data.clear()
        data.addAll(newData)
        calculateDiff.dispatchUpdatesTo(this)

//        data.clear()
//        data.addAll(newData)
//        notifyDataSetChanged()
    }

    /**
     * 追加数据，范围局部刷新
     */
//    fun addData(newData: MutableList<MyModel>) {
//        val size = data.size
//        data.addAll(newData)
//        notifyItemRangeInserted(size - 1, newData.size) //范围刷新
//    }
    //RecyclerView 正在计算布局或滚动时调用了数据更新操作
    //当 RecyclerView 正在滚动或计算布局时，
    // 直接调用了 notifyItemRangeInserted()，
    // 会导致 IllegalStateException
    fun addData(newData: MutableList<MyModel>) {
        if (newData.isEmpty() || isLoading) return

        // 如果正在计算布局，延迟执行
        if (recyclerView?.isComputingLayout == true) {
            recyclerView?.post { addData(newData) }
            return
        }

        isLoading = true
        val startPos = data.size
        data.addAll(newData)
        notifyItemRangeInserted(startPos, newData.size)
        isLoading = false
    }

    fun addData(myModel: MyModel) {
        data.add(myModel)
        notifyItemInserted(data.size) //局部更新
    }

    fun removeData(position: Int) {
        data.removeAt(position)
        notifyItemRemoved(position)//局部更新
    }

    fun moveData(from: Int, to: Int) {
        Collections.swap(data, from, to)
        notifyItemMoved(from, to)//局部更新
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        LoggerUtils.d(TAG, "onCreateViewHolder: ")
        return MyViewHolder(View.inflate(parent.context, R.layout.item, null))
    }

    override fun getItemCount(): Int {
        return data.size
    }

    /**
     * 判断是否预加载
     */
//    private fun checkPreLoad(position: Int) {
//        if (onPreload != null && scrollState != RecyclerView.SCROLL_STATE_IDLE && position == data.size - preloadItemCount - 1) {
//            onPreload.invoke()
//        }
//    }
    //RecyclerView 正在计算布局或滚动时调用了数据更新操作
    private fun checkPreLoad(position: Int) {
        if (onPreload != null &&
            position >= data.size - preloadItemCount - 1 &&
            position != lastPreLoadPosition &&
            !isLoading
        ) {
            lastPreLoadPosition = position
            recyclerView?.post {  // 使用 recyclerView 的 post 方法
                if (scrollState == RecyclerView.SCROLL_STATE_IDLE) {
                    onPreload.invoke()
                }
            }
        }
    }
//payloads 参数：当调用 notifyItemChanged(position, payload) 时，payloads 会携带需要局部刷新的数据，避免整个 Item 重新绑定。
    override fun onBindViewHolder(holder: MyViewHolder, position: Int, payloads: MutableList<Any>) {
        //1-判断是否到达倒数第几个
        checkPreLoad(position)

        if (payloads.isEmpty()) {//没有增量数据，调用父类方法完整刷新 Item。

            super.onBindViewHolder(holder, position, payloads)
        } else {

            when (payloads[0]) {//payloads[0] 是一种约定俗成的写法，表示“取第一个局部刷新标识
                "like" -> {
                    LoggerUtils.d(TAG, "onBindViewHolder局部增量刷新like: $position")
                    if (data[position].isLike) {
                        holder.ivLike.setImageResource(R.drawable.like)
                    } else {
                        holder.ivLike.setImageResource(R.drawable.like_un)
                    }
                }

                "name" -> {
                    LoggerUtils.d(TAG, "onBindViewHolder局部增量刷新name: $position")
                    holder.tv.text = data[position].name
                }

                "url" -> {
                    LoggerUtils.d(TAG, "onBindViewHolder局部增量刷新url: $position")
                    GlideApp.with(holder.itemView).load(data[position].url).into(holder.iv)
                }
            }
        }

    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        LoggerUtils.d(TAG, "onBindViewHolder: $position")
        GlideApp.with(holder.itemView).load(data[position].url).into(holder.iv)
        holder.tv.text = data[position].name
        if (data[position].isLike) {
            holder.ivLike.setImageResource(R.drawable.like)
        } else {
            holder.ivLike.setImageResource(R.drawable.like_un)
        }

        //不要在这里设置点击事件，onBindViewHolder多次调用
//        holder.tv.setOnClickListener {
//            onImageClick.invoke(data[position].url)
//        }
    }

    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val iv: ImageView
        val tv: TextView
        val ivLike: ImageView

        init {
            iv = itemView.findViewById(R.id.iv)
            tv = itemView.findViewById(R.id.tv)
            ivLike = itemView.findViewById(R.id.iv_like)
            //优化四：设置点击事件
            iv.setOnClickListener {
                onImageClick?.invoke(data[bindingAdapterPosition].url)
            }
            ivLike.setOnClickListener {
                onLikeClick?.invoke(bindingAdapterPosition)
            }
        }

    }
}